<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- 新增角色按钮 -->
        <el-row style="height:60px">
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="showRoleDialog"
          >新增角色</el-button>
        </el-row>
        <!-- 表格 -->
        <el-table :data="roleList">
          <el-table-column label="序号" width="120" type="index" />
          <el-table-column label="角色名称" width="240" prop="name" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="{row}">
              <el-button size="small">分配权限</el-button>
              <el-button size="small" @click="editRole(row.id)">编辑</el-button>
              <el-button size="small" type="danger" @click="fetchDelRole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页组件 -->
          <el-pagination
            layout="prev,pager,next"
            :total="total"
            :page-size="params.pagesize"
            @current-change="pageChange"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 弹框 -->
    <addRole
      :show-dialog="showDialog"
      :cou-id="couId"
      @close-dialog="closeDialog"
      @updata-List="fetchRoleList"
    />
  </div>
</template>

<script>
import { getRoleList, deleteRole } from '@/api/setting'
import addRole from '@/views/Setting/components/add-role.vue'
export default {
  name: 'Setting',
  components: {
    addRole
  },
  data() {
    return {
      roleList: [],
      params: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      showDialog: false,
      couId: ''
    }
  },
  created() {
    this.fetchRoleList()
  },
  methods: {
    // 获取列表数据
    async fetchRoleList() {
      const res = await getRoleList(this.params)
      this.roleList = res.rows
      this.total = res.total
      console.log(res)
    },

    // 页码发生变化时重新调用接口发送请求
    pageChange(page) {
      this.params.page = page
      this.fetchRoleList()
    },

    // 删除功能
    fetchDelRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 调用删除接口
        await deleteRole(id)
        // 更新列表
        this.fetchRoleList()
        // 提示用户
        this.$message.success('删除角色成功')
      }).catch()
    },

    // 添加功能
    showRoleDialog() {
      this.showDialog = true
    },

    // 关闭弹窗
    closeDialog() {
      this.showDialog = false
    },

    editRole(id) {
      this.showDialog = true
      this.couId = id
    }
  }
}
</script>
